package com.moming.web;

import com.moming.pojo.User;
import com.moming.service.UserService;
import com.moming.util.StandardPasswordUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    UserService userService= new UserService();
    StandardPasswordUtil standardPasswordUtil = new StandardPasswordUtil();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //获取数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //获取用户填写的验证码
        String checkCode = request.getParameter("checkCode");
        //封装数据
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        //判断密码是否符合规范,调用工具类,判断密码是否是大小写字母、数字、特殊字符中的至少三种
        boolean b = standardPasswordUtil.checkPasswordRule(password);
        if(!b){
            //密码格式错误,跳转到注册页面
            request.setAttribute("msg1", "密码格式错误");
            //转发
            request.getRequestDispatcher("/register.jsp").forward(request,response);
            return;
        }
        //获取服务器域中的验证码
        HttpSession session = request.getSession();
        String checkCode1 = (String) session.getAttribute("checkCode");
        //如果填写的验证码不一致直接退出,不再执行下面的代码
        if(!checkCode.equalsIgnoreCase(checkCode1)){
            //验证码不一致,跳转到注册页面
            request.setAttribute("msg", "验证码填写错误");
            //转发
            request.getRequestDispatcher("/register.jsp").forward(request,response);
            return;
        }
        //调用service层
        boolean f = userService.register(user);
        if(f){
            //注册成功,跳转到登录页面
            request.setAttribute("msg", "注册成功,请登录");
            //转发
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }else {
            //注册失败,跳转到注册页面
            request.setAttribute("msg", "用户名已存在");
            //转发
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}